<?php

namespace app\admin\model;

use addons\wechat\library\Config;
use EasyWeChat\Factory;
use think\Db;
use think\Model;

class WechatResponse extends Model
{

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

	public static function init()
    {
        self::afterWrite(function ($row) {
			if($row->data['type'] == 'image' && (!isset($row->origin['id']) || $row->origin['content'] !== $row->data['content'])){
				// 图片上传到微信资源库
				$content = (array)json_decode($row->data['content'], true);
				if(isset($content['image']) && $content['image']){
					$app = Factory::officialAccount(Config::load());
					$res = $app->material->uploadImage(ROOT_PATH.'public'.$content['image']);
					Db::name('wechat_response')->where('id', $row->id)->update(['media_id' => $res['media_id']]);
				}
			}
        });
    }
}
